const Results = require('../../config/results');
const {sign} = require('jsonwebtoken')
const db = require('../../dbContorller/curd');
const KEY = require('../../config/Key')
const md5 = require('js-md5')
let writeErrLog = require('../../log/writeErrLog')
module.exports = {
    handleLogin: async function (req, res) {
        let {username, password} = req.body;
        let data, user
        try {
            data = await db.ExactFind('user', 'username', username)
        } catch (e) {
            writeErrLog(undefined, e.name, e.code, e.message)
        }
        console.log('data', data)

        if (data && data.results) {
            if (data.results.length === 0) return res.status(500).json(Results.fail(500, '用户名不存在', null))
            user = data.results[0] //用户名是不可以重复的!
            if (user.password !== md5(md5(password))) return res.status(500).json(Results.fail(500, '密码不正确', null))
        } else {
            return res.status(500).json(Results.fail(500, '服务器维护中,请稍后再试!', null));
        }
        delete user.password
        // 拿到post过来的数据 这要归功于 const bodyParser = require('body-parser'); 它解析了post表单的数据
        let token = sign({...user}, KEY, {
            expiresIn: 60 * 60 * 24 * 0.1 //这里是毫秒
        })
        return res.json(Results.success(200, "ok", {token})).status(200)
    },

    handleLogout: function (req, res, next) {
        res.status(200).json(Results.success(200, "ok", null))
    }
}
